//
//  PayViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/22.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit
enum PayType{
    case Bill,Pos,WX,Ail,Union,None
}
class PayViewController: BaseViewController {
    var cartTable:UITableView!
    var selectCell:UITableViewCell?
    var type:PayType = PayType.None
    var total:String?
    var selectNumber:NSInteger?{
        didSet{
            if let num = selectNumber{
                switch num{
                case 0:
                    type = PayType.Ail
                case 1:
                    type = PayType.Union
                default:break
                }
            }

        }
    }
    var dataArray:[[String]]!
    var imageArray:[[String]]!
    var commitButton:UIButton!
    var orderId:String?
    var payUrl:String?
    var orderObj:PayObjItems?
    var continuePay:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "支付订单"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        cartTable = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, 260), style: UITableViewStyle.Grouped)
        cartTable.backgroundColor = UIColor.clearColor()
        cartTable.separatorStyle = UITableViewCellSeparatorStyle.None
        cartTable.showsHorizontalScrollIndicator = false
        cartTable.showsVerticalScrollIndicator = false
        cartTable.dataSource = self
        cartTable.rowHeight = 60.0
        cartTable.delegate = self
        cartTable.scrollEnabled = false
        cartTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "payId")
        dataArray = [["请支付"],["支付宝支付\n支付宝安全支付","银联支付\n银联高效支付"]]
        imageArray = [["pay_icon"],["pay_zhi","pay_unionpay"]]
        view.addSubview(cartTable)
        
        commitButton = UIButton()
        commitButton.frame=CGRectMake(15, CGRectGetMaxY(cartTable.frame)+30, view.bounds.size.width-30, 35)
        commitButton.layer.cornerRadius = 4.0
        commitButton.backgroundColor = commonRedColor
        commitButton.addTarget(self, action: "commitBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        commitButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        commitButton.setTitle("立即支付", forState: UIControlState.Normal)
        commitButton.titleLabel?.font = UIFont.systemFontOfSize(14)
        view.addSubview(commitButton)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "aliPayResult:", name: "alipayResultNotification", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "WXPayResult:", name: "WXPayResultNotification", object: nil)
        // Do any additional setup after loading the view.
    }
    func attributeTextWithString(dstStr:String!)->NSMutableAttributedString{
        let range = (dstStr as NSString).rangeOfString("\n")
        let attr = NSMutableAttributedString(string: dstStr)
        let changeRange = NSMakeRange(range.location, attr.length - range.location)
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attr.length))
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, attr.length))
        attr.addAttribute(NSForegroundColorAttributeName, value:UIColor.lightGrayColor(), range:changeRange)
        attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range:changeRange)
        let paragraph =  NSMutableParagraphStyle()
        paragraph.lineSpacing = 4.0
         attr.addAttribute(NSParagraphStyleAttributeName, value:paragraph, range:NSMakeRange(0, attr.length))
        return attr
    }
    @IBAction func commitBtnClick(){
//        println(orderId)
//        var payWay:String?
//        switch type{
//        case PayType.None:
//            self.showTips("请选择一种支付方式")
//            return
//        case PayType.Bill:
//            payWay = "cashpay"
//        case PayType.Pos:
//            payWay = "pospay"
//        case PayType.Ail:
//            payWay = "alipay"
//        case PayType.Union:
//            payWay = "unionpay"
//        case PayType.WX:
//            payWay = "wxpay"
//        default:break
//        }
        switch type{
        case PayType.WX:
            break
        case PayType.Ail:
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(orderId!, forKey: "order_id")
            request.requestStart("/appaliapy/payment/getorder", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            if let obj = dic!.getPayWayReturn(){
                                self.orderObj = obj
                                self.handleWhenOrderReturnSuccess()
                            }
                        }
                    }
                    //                self.tableDataSource = (dic?.pareseDataToCartListArray())!
                    //                self.totalMoney = dic?["data"]?["base_total"] as? String
                    //                dispatch_async(dispatch_get_main_queue()){
                    //                    self.cartTable.reloadData()
                    //                    self.moneyLabel.text = self.totalMoney
                    //                }
                }
                else{
                    self.showTips("加载失败")
                }
            })
            self.showProcess("加载中...")
        case PayType.Union:
            let request = NetWorkHelper()
            let parameters = NSMutableDictionary()
            parameters.setObject(orderId!, forKey: "order_id")
            request.requestStart("/appunionpay/payment/getOrder", parameters: parameters,compeleteHandle:{ (data, response, error)  in
                dispatch_async(dispatch_get_main_queue()){
                    self.hiddenProcessView()
                }
                if error == nil{
                    var dic:NSDictionary?
                    do {
                        dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                    } catch let error as NSError {
                        print(error)
                        return
                    }
                    if (dic?["result"])! as! String == "0"{
                        dispatch_async(dispatch_get_main_queue()){
                            if let obj = dic!.getPayWayReturn(){
                                self.orderObj = obj
                                self.handleWhenOrderReturnSuccess()
                            }
                        }
                    }
                    //                self.tableDataSource = (dic?.pareseDataToCartListArray())!
                    //                self.totalMoney = dic?["data"]?["base_total"] as? String
                    //                dispatch_async(dispatch_get_main_queue()){
                    //                    self.cartTable.reloadData()
                    //                    self.moneyLabel.text = self.totalMoney
                    //                }
                }
                else{
                    self.showTips("加载失败")
                }
            })
            self.showProcess("加载中...")
        default:break
        }
    }
    func handleWhenOrderReturnSuccess(){
        switch type{
        case PayType.Ail:
            //调用阿里支付
            var amount,inputCharset,itBPay,notifyUrl,partnerId,paymentType,privateKey,productDescription,productName,sellerAccount,tradeNo:String?
            if let input = self.orderObj?.payData?["amount"] as? NSString{
                amount = "\(input.floatValue)"
            }
            if let input = self.orderObj?.payData?["inputCharset"] as? String{
                inputCharset = input
            }
            if let input = self.orderObj?.payData?["itBPay"] as? NSNumber{
                itBPay = "\(input.floatValue)"
            }
            if let input = self.orderObj?.payData?["notifyUrl"] as? String{
                notifyUrl = input
            }
            if let input = self.orderObj?.payData?["partnerId"] as? String{
                partnerId = input
            }
            if let input = self.orderObj?.payData?["paymentType"] as? String{
                paymentType = input
            }
            if let input = self.orderObj?.payData?["privateKey"] as? String{
                privateKey = input
            }
            if let input = self.orderObj?.payData?["productDescription"] as? String{
                productDescription = input
            }
            if let input = self.orderObj?.payData?["productName"] as? String{
                productName = input
            }
            if let input = self.orderObj?.payData?["sellerAccount"] as? String{
                sellerAccount = input
            }
            if let input = self.orderObj?.payData?["outTradeNo"] as? String{
                tradeNo = input
            }
//            AlipayRequestConfig.alipayWithPartner(partnerId, seller:sellerAccount, tradeNO:tradeNo, productName:productName, productDescription:productDescription, amount:amount, notifyURL: notifyUrl, itBPay:itBPay)
            AlipayRequestConfig.alipayWithPartner(partnerId, seller: sellerAccount, tradeNO: tradeNo, productName: productName, productDescription: productDescription, amount: amount, notifyURL: notifyUrl, service: "mobile.securitypay.pay", paymentType: "1", inputCharset: "UTF-8", itBPay: "30m", privateKey: privateKey, appScheme:kAppScheme)
        case PayType.Union:
            //调用银联支付
            if let dic = self.orderObj?.payData{
                let tn = dic["tn"] as! String
                UPPayPlugin.startPay(tn, mode: "00", viewController: self, delegate:self)
            }
            else{
                self.showTips("支付信息为空")
            }
//        case PayType.WX:
//            //调用微信支付
//            
//            if let dic = self.orderObj?.payData{
//                let wxRequestManger = payRequsestHandler()
//                var amount:String?
//                if let input = self.orderObj?.order?.amount {
//                    let num = input as NSString
//                    amount = "\(num.integerValue*100)"
//                }
//                wxRequestManger.setID(dic["appId"] as! String, mch_id: dic["partnerId"] as! String, key: dic["apiKey"] as! String)
//                let adic = wxRequestManger.sendPay_demo(dic["notifyUrl"] as! String, out_trade_no: dic["out_trade_no"] as! String,ipAddress:PayHelper.getIFAddresses()[0],total_fee:amount)
//                let timestamp = adic["timestamp"] as! NSString
//                let request = PayReq()
//                request.openID =  adic["appid"] as! String
//                request.partnerId =  adic["partnerid"] as! String
//                request.prepayId =  adic["prepayid"] as! String
//                request.nonceStr =  adic["noncestr"] as! String
//                request.timeStamp = UInt32(timestamp.intValue)
//                request.package =  adic["package"] as! String
//                request.sign =  adic["sign"] as! String
//                WXApi.sendReq(request)
//            }
//            else{
//                self.showTips("支付信息为空")
//            }
        default:break
        }
    }

    func  goBack(){
        if continuePay{
            self.navigationController?.popViewControllerAnimated(true)
        }
        else{
            self.navigationController?.popToRootViewControllerAnimated(true)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    func aliPayResult(notify:NSNotification){
        let resultDic = notify.object as! NSDictionary
        if let code = resultDic["resultStatus"] as? String{
            if code == "9000"{
//                self.performSegueWithIdentifier("showOrderStatusFromPayView", sender: self)
            }
            else{
                self.showTips("支付未成功")
            }
        }
    }
    func WXPayResult(notify:NSNotification){
        let response = notify.object as! PayResp
        switch response.errCode{
        case 0:
            print("支付成功")
//            self.performSegueWithIdentifier("showOrderStatusFromPayView", sender: self)
            if continuePay{
                self.navigationController?.popViewControllerAnimated(true)
            }
            else{
                self.navigationController?.popToRootViewControllerAnimated(true)
            }
        default:
            let str = NSString(format: "支付失败,%d", response.errCode)
            let alerView = UIAlertView(title: "支付结果", message: str as String, delegate: nil, cancelButtonTitle: "确定")
            alerView.show()
        }
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
}
extension PayViewController:UPPayPluginDelegate{
    func UPPayPluginResult(result:String){
        switch result{
        case "success":
            print("支付成功")
//            self.performSegueWithIdentifier("showOrderStatusFromPayView", sender: self)
            if continuePay{
                self.navigationController?.popViewControllerAnimated(true)
            }
            else{
                 self.navigationController?.popToRootViewControllerAnimated(true)
            }
        case "fail":
            self.showTips("支付失败")
        case "cancel":
            self.showTips("支付已取消")
        default:break
        }
    }
}
extension PayViewController:UITableViewDataSource,UITableViewDelegate{
     func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return dataArray.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataArray[section].count
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        if section == 0 {
            return 10.0
        }
        return 30.0
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        if section == 0 {
            return nil
        }
        let lbl1 = UILabel(frame: CGRectMake(0, 0,tableView.bounds.size.width,30))
        lbl1.text = "    请选择支付方式"
        lbl1.textColor = UIColor.darkGrayColor()
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(12)
        return lbl1
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("payId", forIndexPath: indexPath)
        cell.textLabel?.frame = cell.contentView.bounds
        cell.textLabel?.textAlignment = NSTextAlignment.Left
        
        if indexPath.section == 0{
            cell.textLabel?.font = UIFont.systemFontOfSize(14)
            cell.textLabel?.text = dataArray[indexPath.section][indexPath.row]
            let lbl1 = UILabel(frame: CGRectMake(0, 0,120,30))
            lbl1.text = "¥"+self.total!
            lbl1.textColor = commonRedColor
            lbl1.textAlignment = NSTextAlignment.Right
            lbl1.font = UIFont.systemFontOfSize(14)
            cell.accessoryView = lbl1
        }
        else{
            let sepView = UIView(frame: CGRectMake(0,cell.contentView.bounds.size.height-1, cell.contentView.bounds.size.width, onePix))
            sepView.backgroundColor = view.backgroundColor
            cell.contentView.addSubview(sepView)
            let selectImageView = UIImageView(frame: CGRectMake(0, 0, 20, 20))
            selectImageView.image = UIImage(named:"nor_checkbox")
            cell.accessoryView = selectImageView
            cell.textLabel?.attributedText = self.attributeTextWithString(dataArray[indexPath.section][indexPath.row])

        }
        cell.imageView?.image = UIImage(named: imageArray[indexPath.section][indexPath.row])
        cell.textLabel?.numberOfLines = 0
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        cell.accessoryType = UITableViewCellAccessoryType.None
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        if indexPath.section == 0 {
            return 40
        }
        return 50
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        if indexPath.section == 0 {
            return
        }
        if let cell = selectCell{
            if let imageview = cell.accessoryView as? UIImageView{
                imageview.image = UIImage(named:"nor_checkbox")
            }
        }
        if let sCell = tableView.cellForRowAtIndexPath(indexPath){
            if let imageview = sCell.accessoryView as? UIImageView{
                imageview.image = UIImage(named:"down_checkbox")
            }
            selectNumber = indexPath.row
            selectCell = sCell
        }
    }
}